import React, { useEffect, useState } from "react";
import { TagColumn } from "./column";
import { Table, Input, Button, Popconfirm, message } from "antd";
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { queryAllTags, deleteTag, deleteTags } from "@/api/tag.js";
import tagStyle from "./tag.module.scss";
import TagDialog from "./Tag/tagDialog";

export default function Tag() {
  const [messageApi, contextHolder] = message.useMessage();
  const [id, setId] = useState(-1);
  const [type, setType] = useState(1);
  const [visible, setVisible] = useState(false);
  const [list, setList] = useState([]);
  const [paginationObj, setPaginationObj] = useState({ page: 1, size: 10 });
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, SetselectedRowKeys] = useState();
  useEffect(() => {
    getList();
  }, []);

  const handleSearch = (e) => {
    setSearch(e.target.value);
  };

  const changeVisible = (type, id) => {
    if (id) {
      setId(id);
    } else {
      setId(-1);
    }
    setVisible((pre) => !pre);
    changeType(type);
  };
  const deleteConfirm = async (id) => {
    console.log("confirm");
    try {
      const res = await deleteTag({ id });
      if (res.code === 200) {
        messageApi.open({
          type: "success",
          content: "删除成功！",
          duration: 2,
        });
        getList();
      } else {
        messageApi.error("删除失败");
      }
    } catch (error) {
      messageApi.error("删除失败");
    }
  };
  const handleDeleteSelectConfirm = async () => {
    const ids = selectedRowKeys.join(",");
    console.log(ids, "--ids");
    try {
      const res = await deleteTags({ ids });
      if (res.code === 200) {
        messageApi.open({
          type: "success",
          content: "删除成功！",
          duration: 2,
        });
        getList();
      } else {
        messageApi.error("删除失败");
      }
    } catch (error) {
      messageApi.error("删除失败");
    }
  };

  // 请求tag'列表
  const getList = async (params = { page: 1, size: 10 }) => {
    setLoading((pre) => !pre);
    const res = await queryAllTags({ tagName: search, ...params });
    console.log("taglist", res);
    setList(res.data);
    setPaginationObj({
      page: res.currentPage,
      size: res.pageSize,
      total: res.total,
    });
    setLoading((pre) => !pre);
  };
  // 修改对话框类型
  const changeType = (type) => {
    setType(type);
  };
  // 选中的keys
  const onSelectChange = (newSelectedRowKeys, selectedRow) => {
    SetselectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handlePageChange = (page, size) => {
    getList({ page, size });
  };

  const handleSizeChange = (page, size) => {
    getList({ page, size });
  };

  const columns = TagColumn({ changeVisible, deleteConfirm });

  return (
    <div className={tagStyle.tag}>
      {contextHolder}
      <TagDialog
        isOpen={visible}
        onChange={changeVisible}
        type={type}
        id={id}
        getList={getList}
      />
      <div className={tagStyle.top}>
        <div className={tagStyle.search}>
          <h3>标签名称</h3>
          <Input
            placeholder="请输入标签名称"
            style={{ width: "200px", marginRight: "10px" }}
            value={search}
            onChange={handleSearch}
          />
          <Button
            icon={<SearchOutlined />}
            type="primary"
            className={tagStyle["ant-btn"]}
            onClick={() => getList()}
          >
            查找
          </Button>
          <Button
            icon={<RedoOutlined />}
            className={tagStyle["ant-btn"]}
            onClick={() => setSearch("")}
          >
            重置
          </Button>
        </div>
        <div className={tagStyle.action}>
          <Button
            icon={<PlusOutlined />}
            className={tagStyle["ant-btn"]}
            type="primary"
            onClick={() => changeVisible(2)}
          >
            添加
          </Button>
          <Popconfirm
            title="提示"
            description="确定删除选中的标签吗?"
            cancelText="取消"
            okText="确认"
            onConfirm={handleDeleteSelectConfirm}
          >
            <Button
              icon={<DeleteOutlined />}
              danger
              type="primary"
              className={tagStyle["ant-btn"]}
              disabled={
                selectedRowKeys && selectedRowKeys.length > 0 ? false : true
              }
            >
              删除
            </Button>
          </Popconfirm>
        </div>
      </div>

      <div className={tagStyle['table-container']}>
        <Table
          columns={columns}
          dataSource={list}
          rowSelection={rowSelection}
          rowKey={(record) => record.id}
          loading={loading}
          pagination={{
            pageSize: paginationObj.pageSize,
            current: paginationObj.currentPage,
            pageSizeOptions: [3, 5, 10, 20],
            showSizeChanger: true,
            total: paginationObj.total,
            showTotal: (total) => `共${total}条`,
            onChange: handlePageChange,
            onShowSizeChange: handleSizeChange,
          }}
        />
      </div>
    </div>
  );
}
